import 'package:flutter/material.dart';
import 'package:sale/widgets/common_widgets.dart';
import 'package:sale/constants/app_constants.dart';
import 'dart:ui';
import 'dart:math';
import 'package:provider/provider.dart';
import 'package:sale/utils/auth_state.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
    ));

    _slideAnimation = Tween<Offset>(
      begin: const Offset(0.0, 0.1),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: const Interval(0.0, 0.6, curve: Curves.easeOutCubic),
    ));

    // 开始动画
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Widget _buildHeader() {
    final isSmallScreen = MediaQuery.of(context).size.width < 800;

    return Container(
      padding: EdgeInsets.symmetric(
          horizontal: isSmallScreen ? 16 : 32,
          vertical: isSmallScreen ? 16 : 20),
      child: Column(
        children: [
          ShaderMask(
            blendMode: BlendMode.srcIn,
            shaderCallback: (bounds) => LinearGradient(
              colors: [
                AppConstants.primaryColor,
                Colors.purple.shade700,
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ).createShader(bounds),
            child: Text(
              '一体化场景解决方案',
              textAlign: TextAlign.center,
              style: AppConstants.headingStyle.copyWith(
                fontSize: isSmallScreen ? 28 : 36,
                fontWeight: FontWeight.w900,
                letterSpacing: 2,
              ),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '中国电信西宁分公司',
            style: TextStyle(
              fontSize: isSmallScreen ? 14 : 16,
              color: AppConstants.textColor.withOpacity(0.9),
              fontWeight: FontWeight.w500,
              letterSpacing: 0.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProductCards(BuildContext context) {
    // 获取屏幕尺寸
    final screenSize = MediaQuery.of(context).size;
    // 根据屏幕宽度调整布局
    final isSmallScreen = screenSize.width < 800;
    final cardSpacing = isSmallScreen ? 16.0 : 24.0;

    if (isSmallScreen) {
      // 小屏幕使用垂直布局，每行一个卡片
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          children: [
            _ProductSelectionCard(
              title: '智慧酒店',
              description: '酒店专用网络解决方案\n千兆宽带组网·智能设备管理',
              onTap: () => Navigator.pushNamed(context, '/hotel'),
            ),
            SizedBox(height: cardSpacing),
            _ProductSelectionCard(
              title: '美好家',
              description: '家庭智能网络解决方案\n全屋WiFi覆盖·智能家居生态',
              onTap: () => Navigator.pushNamed(context, '/family'),
            ),
            SizedBox(height: cardSpacing),
            _ProductSelectionCard(
              title: '智慧会议',
              description: '会议室专用网络解决方案\n高清视频会议·智能协作办公',
              onTap: () => Navigator.pushNamed(context, '/meeting'),
            ),
            SizedBox(height: cardSpacing),
            _ProductSelectionCard(
              title: '智慧办公',
              description: '办公场所专用网络解决方案\n稳定连接·高效协同工作',
              onTap: () => Navigator.pushNamed(context, '/work'),
            ),
          ],
        ),
      );
    } else {
      // 大屏幕使用网格布局
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          children: [
            // 第一行：智慧酒店和美好家
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 智慧酒店卡片
                _ProductSelectionCard(
                  title: '智慧酒店',
                  description: '酒店专用网络解决方案\n千兆宽带组网·智能设备管理',
                  onTap: () => Navigator.pushNamed(context, '/hotel'),
                ),
                SizedBox(width: cardSpacing),
                // 美好家卡片
                _ProductSelectionCard(
                  title: '美好家',
                  description: '家庭智能网络解决方案\n全屋WiFi覆盖·智能家居生态',
                  onTap: () => Navigator.pushNamed(context, '/family'),
                ),
              ],
            ),
            SizedBox(height: cardSpacing), // 行间距
            // 第二行：智慧会议和智慧办公
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 智慧会议
                _ProductSelectionCard(
                  title: '智慧会议',
                  description: '会议室专用网络解决方案\n高清视频会议·智能协作办公',
                  onTap: () => Navigator.pushNamed(context, '/meeting'),
                ),
                SizedBox(width: cardSpacing),
                // 智慧办公
                _ProductSelectionCard(
                  title: '智慧办公',
                  description: '办公场所专用网络解决方案\n稳定连接·高效协同工作',
                  onTap: () => Navigator.pushNamed(context, '/work'),
                ),
              ],
            ),
          ],
        ),
      );
    }
  }

  Widget _buildFooter() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.copyright_rounded,
                size: 16,
                color: AppConstants.textColor.withOpacity(0.7),
              ),
              const SizedBox(width: 4),
              Text(
                '2025 云中台',
                style: TextStyle(
                  fontSize: 14,
                  color: AppConstants.textColor.withOpacity(0.7),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          const SizedBox(height: 6),
          Text(
            '智慧网络 · 随心所享',
            style: TextStyle(
              fontSize: 12,
              color: AppConstants.textColor.withOpacity(0.6),
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final authState = context.watch<AuthState>();
    final user = authState.user;
    final screenSize = MediaQuery.of(context).size;

    return Scaffold(
      body: SafeArea(
        child: GradientBackground(
          child: Column(
            children: [
              // 顶部用户信息栏
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.1),
                  border: Border(
                    bottom: BorderSide(
                      color: Colors.white.withOpacity(0.2),
                    ),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        const Icon(
                          Icons.person_outline,
                          color: Colors.white,
                          size: 24,
                        ),
                        const SizedBox(width: 8),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              user?['name'] ?? '未登录',
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            Text(
                              user?['department'] ?? '',
                              style: TextStyle(
                                color: Colors.white.withOpacity(0.7),
                                fontSize: 14,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    IconButton(
                      icon: const Icon(
                        Icons.logout_rounded,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        showDialog(
                          context: context,
                          builder: (context) => Dialog(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16),
                            ),
                            insetPadding:
                                const EdgeInsets.symmetric(horizontal: 40),
                            child: Container(
                              width: 280,
                              padding: const EdgeInsets.all(16),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(16),
                              ),
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  const Icon(
                                    Icons.logout_rounded,
                                    color: Colors.red,
                                    size: 32,
                                  ),
                                  const SizedBox(height: 12),
                                  const Text(
                                    '退出登录',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  const SizedBox(height: 8),
                                  const Text(
                                    '确定要退出登录吗？',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  const SizedBox(height: 16),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      TextButton(
                                        onPressed: () => Navigator.pop(context),
                                        style: TextButton.styleFrom(
                                          backgroundColor: Colors.grey.shade200,
                                          minimumSize: const Size(90, 36),
                                          shape: RoundedRectangleBorder(
                                            borderRadius:
                                                BorderRadius.circular(8),
                                          ),
                                        ),
                                        child: const Text(
                                          '取消',
                                          style: TextStyle(
                                            color: Colors.black87,
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                      ),
                                      ElevatedButton(
                                        onPressed: () {
                                          context.read<AuthState>().logout();
                                          Navigator.pop(context);
                                          Navigator.pushReplacementNamed(
                                              context, '/login');
                                        },
                                        style: ElevatedButton.styleFrom(
                                          backgroundColor: Colors.red,
                                          foregroundColor: Colors.white,
                                          minimumSize: const Size(90, 36),
                                          shape: RoundedRectangleBorder(
                                            borderRadius:
                                                BorderRadius.circular(8),
                                          ),
                                        ),
                                        child: const Text(
                                          '确定',
                                          style: TextStyle(
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
              // 主要内容区域
              Expanded(
                child: Center(
                  child: ConstrainedBox(
                    constraints: BoxConstraints(
                      maxWidth: screenSize.width,
                      maxHeight: screenSize.height,
                    ),
                    child: SlideTransition(
                      position: _slideAnimation,
                      child: FadeTransition(
                        opacity: _fadeAnimation,
                        child: SingleChildScrollView(
                          child: ConstrainedBox(
                            constraints: BoxConstraints(
                              minHeight: screenSize.height - 100, // 减去顶部栏的高度
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                // 标题
                                _buildHeader(),
                                const SizedBox(height: 20),
                                // 产品选择卡片
                                _buildProductCards(context),
                                // 页脚
                                const SizedBox(height: 20),
                                _buildFooter(),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 产品选择卡片组件
class _ProductSelectionCard extends StatefulWidget {
  final String title;
  final String description;
  final VoidCallback onTap;

  const _ProductSelectionCard({
    required this.title,
    required this.description,
    required this.onTap,
  });

  @override
  State<_ProductSelectionCard> createState() => _ProductSelectionCardState();
}

class _ProductSelectionCardState extends State<_ProductSelectionCard>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _scaleAnimation;
  bool _isHovered = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(begin: 1.0, end: 1.03).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeOutCubic),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 根据产品标题生成不同的渐变色
    List<Color> cardGradient;
    IconData cardIcon;

    switch (widget.title) {
      case '智慧酒店':
        cardGradient = [Color(0xFF3B82F6), Color(0xFF2563EB)];
        cardIcon = Icons.hotel_rounded;
        break;
      case '美好家':
        cardGradient = [Color(0xFF8B5CF6), Color(0xFF6D28D9)];
        cardIcon = Icons.home_rounded;
        break;
      case '智慧会议':
        cardGradient = [Color(0xFFEC4899), Color(0xFFBE185D)];
        cardIcon = Icons.groups_rounded;
        break;
      case '智慧办公':
        cardGradient = [Color(0xFF10B981), Color(0xFF047857)];
        cardIcon = Icons.work_rounded;
        break;
      default:
        cardGradient = AppConstants.primaryGradient;
        cardIcon = Icons.devices_rounded;
    }

    return MouseRegion(
      cursor: SystemMouseCursors.click,
      onEnter: (_) {
        setState(() {
          _isHovered = true;
        });
        _controller.forward();
      },
      onExit: (_) {
        setState(() {
          _isHovered = false;
        });
        _controller.reverse();
      },
      child: GestureDetector(
        onTap: widget.onTap,
        child: ScaleTransition(
          scale: _scaleAnimation,
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 250),
            width: MediaQuery.of(context).size.width < 800
                ? min(MediaQuery.of(context).size.width * 0.85,
                    AppConstants.productCardWidth)
                : AppConstants.productCardWidth,
            height: MediaQuery.of(context).size.width < 800
                ? min(MediaQuery.of(context).size.width * 0.55,
                    AppConstants.productCardHeight)
                : AppConstants.productCardHeight,
            decoration: BoxDecoration(
              borderRadius:
                  BorderRadius.circular(AppConstants.largeBorderRadius),
              boxShadow: [
                BoxShadow(
                  color: _isHovered
                      ? Colors.black.withOpacity(0.25)
                      : Colors.black.withOpacity(0.15),
                  blurRadius: _isHovered ? 20 : 10,
                  offset: _isHovered ? const Offset(0, 10) : const Offset(0, 5),
                ),
              ],
            ),
            child: ClipRRect(
              borderRadius:
                  BorderRadius.circular(AppConstants.largeBorderRadius),
              child: Stack(
                children: [
                  // 渐变背景
                  Positioned.fill(
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.15),
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            cardGradient[0].withOpacity(0.15),
                            cardGradient[1].withOpacity(0.25),
                          ],
                        ),
                      ),
                    ),
                  ),

                  // 装饰性圆形渐变
                  Positioned(
                    top: -20,
                    right: -20,
                    child: Container(
                      width: 120,
                      height: 120,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        gradient: RadialGradient(
                          colors: [
                            cardGradient[0].withOpacity(0.3),
                            cardGradient[0].withOpacity(0.0),
                          ],
                        ),
                      ),
                    ),
                  ),

                  // 内容
                  _buildModernContent(cardGradient, cardIcon),

                  // 边框效果
                  Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    child: Container(
                      height: 1.5,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                          colors: [
                            Colors.white.withOpacity(0.1),
                            Colors.white.withOpacity(0.6),
                            Colors.white.withOpacity(0.1),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildModernContent(List<Color> colors, IconData icon) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(24, 20, 24, 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图标
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: colors,
              ),
              boxShadow: [
                BoxShadow(
                  color: colors[0].withOpacity(0.3),
                  blurRadius: 10,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Icon(
              icon,
              color: Colors.white,
              size: 24,
            ),
          ),

          const Spacer(),

          // 标题
          Text(
            widget.title,
            style: AppConstants.cardTitleStyle.copyWith(
              fontSize: 26,
              fontWeight: FontWeight.w900,
              letterSpacing: 1.2,
              height: 1.0,
              color: AppConstants.textColor,
              shadows: [],
            ),
          ),
          const SizedBox(height: 6),

          // 分隔线
          Container(
            height: 2,
            width: 40,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: colors,
              ),
              borderRadius: BorderRadius.circular(1),
            ),
          ),
          const SizedBox(height: 8),

          // 描述
          Text(
            widget.description,
            style: AppConstants.cardDescriptionStyle.copyWith(
              fontSize: 14,
              height: 1.3,
              fontWeight: FontWeight.w500,
              color: AppConstants.textColor.withOpacity(0.8),
              shadows: [],
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
          const SizedBox(height: 12),

          // 按钮
          ModernButton(
            text: '立即查看',
            icon: Icons.arrow_forward_rounded,
            onTap: widget.onTap,
            color: colors[0],
          ),
        ],
      ),
    );
  }
}
